<template>
	<div>
		<picker
			size="mini"
			@change="change"
			:value="index"
			:range="dictList"
			:range-key="dictLabel"
			:disabled="disabled || state == 'disabled'"
		>
			<view class="uni-input">{{ currentLabel }}</view>
		</picker>
	</div>
</template>

<script>
export default {
	name: '',
	components: {},
	props: {
		value: {
			required: false
		},
		state: {
			required: false
		},
		disabled: {
			required: false
		},
		dict: {
			required: false,
			default: () => {}
		},
		label: {
			required: false
		}
	},
	data() {
		return {
			index: undefined,
			current: undefined,
			dictList: []
		};
	},
	computed: {
		currentLabel() {
			let label = this.getDictLabel(this.current);
			return label ?? '请选择数据';
		},
		dictValue() {
			return this.dict?.value ?? 'value';
		},
		dictLabel() {
			return this.dict?.label ?? 'label';
		}
	},
	created() {},
	watch: {
		value: {
			handler: function (val) {
				this.init();
			},
			deep: true,
			immediate: true
		},
		dict: {
			handler: function (val) {
				this.initDict();
			},
			deep: true,
			immediate: true
		}
	},
	mounted() {},
	methods: {
		init() {
			if (this.Empty(this.value)) {
				this.index = undefined;
				return;
			}
			let index = this.dict.list?.findIndex(
				(e) => this.getDictValue(e) === this.value
			);
			this.index = index;
		},
		initDict() {
			if (this.dict?.list?.length > 0) {
				let dictList = this.A_deepClone(this.dict.list);

				if (typeof dictList[0] !== 'object') {
					dictList = [];
					this.dict.list?.map((item) => {
						dictList.push({
							value: item,
							label: item
						});
					});
				}
				let index = dictList.findIndex(
					(e) => this.getDictValue(e) == undefined
				);
				if (index == -1) {
					let obj = {};
					obj[this.dict?.label ?? 'label'] = '无';
					obj[this.dict?.value ?? 'value'] = undefined;
					dictList.unshift(obj);
				}
				this.dictList = dictList;
			}
		},
		change(e) {
			let index = e.detail.value;
			this.current = this.dictList?.[index];
			this.index = index;

			let val = this.getDictValue(this.current);
			this.$emit('change', {
				val,
				item: this.current ?? {}
			});
			this.$emit('input', val);
		},
		getDictLabel(data) {
			return (
				data?.[this.dict?.label] ?? data?.dictLabel ?? data?.label ?? data?.text
			);
		},
		getDictValue(data) {
			return data?.[this.dict?.value] ?? data?.dictValue ?? data?.value;
		}
	}
};
</script>

<style lang="scss" scoped>
.uni-input {
	line-height: 30rpx;
	margin-left: 10rpx;
}
</style>
